

//重构
;(function(){
	var G = {
		is : (function(){
			var Sys = {};
			var ua = navigator.userAgent.toLowerCase();
			var s;
			(s = ua.match(/rv:([\d.]+)\) like gecko/)) ? Sys.ie = s[1] :
			(s = ua.match(/msie ([\d.]+)/)) ? Sys.ie = s[1] :
			(s = ua.match(/firefox\/([\d.]+)/)) ? Sys.firefox = s[1] :
			(s = ua.match(/chrome\/([\d.]+)/)) ? Sys.chrome = s[1] :
			(s = ua.match(/opera.([\d.]+)/)) ? Sys.opera = s[1] :
			(s = ua.match(/version\/([\d.]+).*safari/)) ? Sys.safari = s[1] : 0;
			return Sys
		})()
	}
	var SelectData = {}; //存放已选择的数据
	var oData = {}; //存放ajax一次性抓取的list列表全部数据
	var cData = {}; //数据缓存
	var itemsizeperpage = 15; //每页显示多少条数据
	var resultdatasize = 0; //当前总数据数
	var totalpagesize = 0; //当前总页数
	var curpagenum = 1; //当前在第几页
	var AreaData = {}; //存放省份、市级信息
	var AjaxTimeout = 5 * 1000;
	var URLS = {
		getAreas : "call/getAreas.php",
		getAllListData : "product_package_new.html"
	}
	var Obser = $({});
	
	var seah_inp_text = "景区产品名称或供应商";
	var B = G.is.ie;
	
	
	
	/*
	{
		"12" : {
			"name" : "福建省",
			"citys" : {
				{ "001" : "福州" },
				{ "002" : "泉州" }
			}
		},
		"11" : {
		
		}
	}
	****/
	
	var Ajaxor = (function(){
		
		//取得所有省份
		function getAllProvs(){
			$.ajax({
				url : URLS.getAreas,
				type : "GET",
				dataType : "json",
				timeout : AjaxTimeout,
				data : {
					act : "getProvince"
				},
				success : function(res){
					if(res && res.length){
						var prov = {};
						for(var i=0,len=res.length; i<len; i++){
							var provId = res[i]["area_id"];
							AreaData[provId]= {};
							AreaData[provId]["name"] = res[i]["area_name"];
						}
						Obser.trigger("buildProvince");
					}else{
						alert("获取城市列表出错")
					}
				},
				error : function(xhr,textStatus){
					if(textStatus && textStatus == "timeout"){
						xhr && xhr.abort && typeof xhr.abort == "function" && xhr.abort();
					}
					alert(textStatus)
				}
			})
		}
		//获得指定省份的所有市级
		function getCitys(parentId){
			if(typeof parentId == "undefined") return;
			var cselect = $("#citySelect");
			
			$.ajax({
				url : URLS.getAreas,
				type : "GET",
				dataType : "json",
				data : {
					act : "getCity",
					parentId : parentId,
					area_deeppath : 2,
					area_id : 381
				},
				success : function(res){
					if(res && res.length){
						cselect.empty();
						cselect.append('<option value="00">全部市(区)</option>');
						AreaData[parentId] = AreaData[parentId] || {};
						AreaData[parentId]["citys"] = AreaData[parentId]["citys"] || {};
						$.each(res,function(index,data){
							AreaData[parentId]["citys"][data.area_id] = data.area_name;
							cselect.append('<option value="'+data.area_id+'">'+data.area_name+'</option>')
						})
					}else{
						alert("获取市级列表失败")
					}
				},
				error : function(xhr,textStatus){
					alert("获取市级列表失败")
				}
			})
		}
		//获得所有列表数据
		function getAllListData(){
			//loading();
			$.ajax({
				url : URLS.getAllListData,
				type : "GET",
				dataType : "JSON",
				timeout : AjaxTimeout,
				data : { "action" : "all" },
				success : function(res){
					if(res && res.total>0){
						oData = res.lists;
						Obser.trigger("ajax.allData.ready");
					}else{
						alert("无数据");
					}
				},
				error : function(xhr,textStatus){
					if(textStatus && textStatus == "timeout"){
						if(xhr && xhr.abort && typeof xhr.abort == "function"){
							xhr.abort();
							alert("请求产品列表超时，请稍后重试。");
						}
					}else{
						alert("请求产品列表出错");
					}
				}
			})
		}
		
		function init(){
			getAllProvs();
			getAllListData();
		}
		
		return {
			getAllProvs : getAllProvs,
			getCitys : getCitys,
			getAllData : getAllListData
		}
		
	})();
	
	var Filtor = (function(){
	
		function filter(json){
			/**************
				json = {
					pid : "省份id"，
					cid : "省份下市级id"，
					keyword : "关键字",
					"type" : "1"
				}
			**/
			json = json || {};
			var pid = json.pid || "00";
			var cid = json.cid || "00";
			var type = json.type || "1";
			var keyword = json.keyword || "";
			var result = {};
			resultdatasize = 0;
			for(var s in cData){
				cData[s] = "undefined";
				delete cData[s];
			}
			result = _filtKeyword(pid,cid,type,keyword);
			for(var i in result){
				resultdatasize++;
				cData[i] = result[i];
			}
			totalpagesize = Math.ceil(resultdatasize/itemsizeperpage);
		}
		function _filtProv(pid){
			var result = {};
			if(pid == "00"){ //取全部
				for(var i in oData){
					result[i] = oData[i];
				}
			}else{ //取某一省份
				for(var s in oData){
					var _pid = oData[s]["areas"][0];
					if(_pid == pid){
						result[s] = oData[s];
					}
				}
			}
			return result;
		}
		function _filtCity(pid,cid){
			var data = _filtProv(pid);
			var result = {};
			if(cid == "00"){
				return data;
			}else{
				for(var i in data){
					var _cid = data[i]["areas"][1];
					if(_cid == cid){
						result[i] = data[i];
					}
				}
				return result
			}
		}
		function _filtKeyword(pid,cid,type,keyword){
			var data = _filtCity(pid,cid);
			var result = {};
			var name = "";
			if(keyword == ""){
				result = _filtCity(pid,cid);
			}else{
				for(var i in data){
					name = type == "1" ? data[i]["title"] : data[i]["apply_dname"];
					if(name.indexOf(keyword) == 0 ){
						result[i] = data[i];
					}
				}
			}
			return result;
		}
		return {
			filter : filter
		}
	})();
	//分页获取缓存数据
	var Getor = (function(){
		//获取第几页
		function getpage(pagenum){
			if(pagenum<1 || pagenum>totalpagesize) return;
			curpagenum = pagenum;
			var begin = (pagenum-1) * itemsizeperpage + 1;
			var end = pagenum * itemsizeperpage;
			var data = _get(begin,end);
			return data;
		}
		function _get(begin,end){
			var data = {};
			var index = 0;
			if(begin<end){
				for(var i in cData){
					index++;
					if(index>=begin && index<=end){
						data[i] = cData[i];
					}
				}
			}
			return data;
		}
		return {
			getpage : getpage
		}
	})();
	//管理分页
	var Pager = (function(){
		var ifBindevent = false;
		function refresh(){
			if(resultdatasize > itemsizeperpage){
				var w = $("#pagenavW");
				w.find(".curentpage").text(curpagenum);
				w.find(".totalpage").text(totalpagesize);
				w.find(".totalItemSize .n").text(resultdatasize);
				$("#pagenavW").show();
			}else{
				$("#pagenavW").hide();
			}
			if(!ifBindevent){
				ifBindevent = true;
				var pagenavW = $("#pagenavW");
				pagenavW.on("click",".prevBtn",function(e){
					_goWhitch(curpagenum-1);
					return false;
				}).on("click",".nextBtn",function(e){
					_goWhitch(curpagenum+1);
					return false;
				}).on("click",".cerPageBtn",function(e){
					_goWhitch($(e.target).val());
					return false;
				}).on("keyup",".pageInp",function(e){
					if(e.keyCode == 13){
						var pagenum = Number($(e.target).val())
						_goWhitch(pagenum);
					}
				}).on("focus",".pageInp",function(e){
					$(e.target).addClass("onfocus");
					$("#cerPageBtn").animate({width:46});
				}).on("blur",".pageInp",function(e){
					$(e.target).removeClass("onfocus");
					$("#cerPageBtn").animate({width:0});
				})
			}
		}
		function _goWhitch(pagenum){
			if(typeof pagenum !== "number"){
				return;
			}else if(pagenum == 0){
				alert("页数必须大于1");
			}else if(pagenum > totalpagesize){
				alert("不存在第"+pagenum+"页 当前最大页数为"+totalpagesize+"页");
			}else{
				var data = Getor.getpage(pagenum);
				_loading();
				setTimeout(function(){
					Buildor.buildData(data);
					curpagenum = pagenum;
					Pager.refresh();
				},0.5*1000);
			}
		}
		function _loading(){
			var loading_html = '<li class="loading" style="text-align:center; line-height:1.5; height:400px;"><p style="color:#aeaeae; font-size:12px; padding-top:300px;">加截数据...</p><img src="images/other/loading_1.gif" alt="" /></li>';
			$("#mlistUl").html(loading_html);
		}
		return { refresh : refresh }
	})();
	var Buildor = (function(){
		function buildProvince(){
			var pselect = $("#provSelect");
			var cselect = $("#citySelect");
			pselect.append('<option value="00">全部省份</option>');
			for(var i in AreaData){
				pselect.append('<option value="'+i+'">'+AreaData[i]["name"]+'</option>');
			}
			cselect.append('<option value="00">全部市区</option>');
		}
		function buildData(data,ifNav){
			
			var str = "";
			var area = null;
			var is_data_empty = true;
			var selectedData = Countor.getSelected();
			for(var i in data){
				is_data_empty = false;
				var cls = "";
				var lid = data[i]["lid"];
				if(selectedData[lid]){
					cls = "selected";
				}
				area = _getArea(data[i]["areas"][0]);
				str += '<li class="itemLi odd '+cls+'">';
				str +=     '<ul class="topUl">';
				str +=         '<li class="tcol_1 tcol"><input type="hidden" name="" class="pid" value="'+data[i]["lid"]+'"/>【'+area.province+' '+data[i]["address"]+'】'+data[i]["title"]+'</li>';
				str +=         '<li class="tcol_2 tcol">'+data[i]["apply_dname"]+'</li>';
				str +=         '<li class="tcol_3 tcol"><select class="ck" name="" id=""><option value="0">不关联</option><option value="1">关联</option></select></li>';
				str +=     '</ul>';
				str +=     '<div class="botW clearfix"><table class="table"><thead><th class="tbcol tbcol_1">票名称</th><th class="tbcol tbcol_2">供货价</th><th class="tbcol tbcol_3">建议零售价</th><th class="tbcol tbcol_6">打包数量</th></thead><tbody>';
				for(var s in data[i]["ticket"]){
					var t = data[i]["ticket"][s];
					var tid = t["pid"];
					var inpOval = 0;
					if(typeof selectedData[lid] !== "undefined"){
						if(typeof selectedData[lid]["tickets"][tid] !== "undefined"){
							inpOval = selectedData[lid]["tickets"][tid]["count"];
						}
					}
					str +=     '<tr><td class="tname tbcol_1"><input type="hidden" value="'+t.pid+'" class="tid" /><input type="hidden" name="" value="'+t.aid+'" class="aid" />'+t.title+'</td><td><i class="yen">&yen;</i><i class="num tprice">'+t.jsprice/100+'</i></td><td><i class="yen">&yen;</i><i class="num sprice">'+t.uprice/100+'</i></td><td class="num"><div class="tcountW"><a href="#" class="minBtn cbtn">-</a><input type="text" value="'+inpOval+'" class="numInp" /><a href="#" class="addBtn cbtn">+</a></div></td></tr>';
				}
				str +=     '</tbody></table><a href="#" class="slideUpBtn"><i class="i">︽</i>收起</a></div>';
				str += '</li>';
			}
			$("#mlistUl").html(str);
			setTimeout(function(){
				$("#mlistUl").children(":first").addClass("selected").find(".botW").slideDown();
			},200);
			
			if(is_data_empty){
				$("#mlistUl").html('<li style="height:200px; line-height:200px; text-align:center; font-size:12px; color:red;">无数据...</style>');
			}
		}
		function _loading(){
			var loading_html = '<li class="loading" style="text-align:center; line-height:1.5; height:400px;"><p style="color:#aeaeae; font-size:12px; padding-top:300px;">加截数据...</p><img src="images/other/loading_1.gif" alt="" /></li>';
			$("#mlistUl").html(loading_html);
		}
		function _getArea(prodid){
			var area = { province : "", city : ""};
			var province = AreaData[prodid] || {};
			area.province = province["name"]
			return area;
		}
		return {
			buildProvince : buildProvince,
			buildData : buildData
		}
		
	})();
	
	var Countor = (function(){
		
		//数据缓存
		var oData = {
			/* "33145" : {
				pname : "景区产品名称",
				tickets : {
					"21544" : {
						name : "",
						count : ""
					},
					"26541" : {
						name : "",
						count : ""
					}
				}
			} */
		};
		
		function getSelected(){
			return oData;
		}
		
		return{
			getSelected : getSelected
		}
		
		
	})();
	
	
	var List = {
		init : function(){
			Filtor.filter({
				pid : "00",
				cid : "00",
				type : "1",
				keyword : ""
			});
			var data = Getor.getpage(1);
			Buildor.buildData(data);
			Pager.refresh();
			List.bindEvent();
		},
		bindEvent : function(){
			var pselect = $("#provSelect");
			var cselect = $("#citySelect");
			var dselect = $("#conSelect");
			var serhInp = $("#serhInp");
			pselect.change(function(e){
				var val = $(e.target).val();
				var result = {};
				cselect.empty();
				cselect.append('<option value="00">全部市(区)</option>');
				if(val !== "00"){ 
					var citys = AreaData[val]["citys"];
					if(citys){ //如果已有缓存
						for(var i in citys){
							cselect.append('<option value="'+i+'">'+citys[i]+'</option>');
						}
					}else{ //如无缓存则ajax取
						Ajaxor.getCitys(val);
					}
				}
				Filtor.filter({
					pid : val,
					cid : "00",
					type : "1",
					keyword : ""
				});
				result = Getor.getpage(1);
				Buildor.buildData(result);
				Pager.refresh();
			})
			cselect.change(function(e){
				var pselect = $("#provSelect");
				var cval = $(e.target).val();
				Filtor.filter({
					pid : pselect.val(),
					cid : cval,
					type : "1",
					keyword : ""
				});
				result = Getor.getpage(1);
				Buildor.buildData(result);
				Pager.refresh();
			})
			serhInp.val(seah_inp_text).on("focus",function(e){
				var t = $(e.target);
				t.addClass("onfocus");
				if(!B || parseFloat(B)>8){
					if(t.val() == seah_inp_text){
						t.val("");
					}
				}
			}).on("blur",function(e){
				var t = $(e.target);
				t.removeClass("onfocus");
				if(!B || parseFloat(B)>8){
					if(t.val() == ""){
						t.val(seah_inp_text);
					}
				}
			}).on("input propertychange",function(e){
				Filtor.filter({
					pid : pselect.val(),
					cid : cselect.val(),
					type : dselect.val(),
					keyword : $(e.target).val()
				})
				result = Getor.getpage(1);
				Buildor.buildData(result);
				Pager.refresh();
			})
			//ie6 7 8不支持input事件 用onpropertychange
			/*if(s && parseFloat(s)<9){
				document.getElementById('serhInp').attachEvent('onpropertychange',function(e) {
					if(e.propertyName.toLowerCase()!='value') return;
					filter($(e.srcElement));
				});
			} */
		}
	};
	
	Obser.on("buildProvince",Buildor.buildProvince);
	Obser.on("ajax.allData.ready",List.init);
	
	
	
	$(function(){
		Ajaxor.getAllProvs();
		Ajaxor.getAllData();
	})
	
	
	
})();



/* {
	"2778_1433": {
        "p_type": "A", 
        "sapply_did": "1433", 
        "title": "08141622", 
        "py": "0", 
        "lid": "2778", 
        "areas": [
            "12", 
            "381", 
            "0"
        ], 
        "ticket": [
            {}
		]
	},
	"2778_1433": {
        "p_type": "A", 
        "sapply_did": "1433", 
        "title": "08141622", 
        "py": "0", 
        "lid": "2778", 
        "areas": [
            "12", 
            "381", 
            "0"
        ], 
        "ticket": [
            {}
		]
	}
}

{
	total : 450,
	list : []
}  */









